<html>
<head>
<title>授权管理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<link rel="shortcut icon" href="resources/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="resources/css/stylemain.css">
<link rel="stylesheet" href="resources/layui/css/layui.css">

<link rel="stylesheet" href="resources/layui/css/treeTable.css">
<link rel="stylesheet" href="resources/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="resources/layui/layui.all.js"></script>
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/base64.js"></script>
</head>
<body>
<table style="margin-top:10px">
	<tr>
		<td>
			<button class="layui-btn layui-btn-sm" onclick="dialog_add()"><i class="layui-icon layui-icon-add-circle"></i> 添加</button>
		</td>
		<td>
			<button class="layui-btn layui-btn-sm" style="margin-left:10px" onclick="dialog_edit()"><i class="layui-icon layui-icon-edit"></i> 修改</button>
		</td>
		<td>
			<button class="layui-btn layui-btn-sm" style="margin-left:10px" onclick="u_cancel('','')"><i class="layui-icon layui-icon-console"></i> 撤销</button>
		</td>
		<td>
			<label style="margin-left:10px">授权时间:</label><input type="text" id="c_start" placeholder="yyyy-MM-dd" class="table_bar_tool">-<input type="text" id="c_end" placeholder="yyyy-MM-dd" class="table_bar_tool">
		</td>
		<td>
			<button class="layui-btn layui-btn-sm" onclick="doSearch()"><i class="layui-icon layui-icon-search"></i> 查询</button>
		</td>
	</tr>
</table>
<input id="user_id" type="text" style="display:none" />
<table class="layui-hide" id="tbl_auth" lay-filter=tbl_auth></table>
<div id="page"></div>

<script id="authadd" type="text/html">
	<form class="layui-form" action="" style="margin-top:20px;width:460px">
		<div class="layui-form-item" id="u_user">
		    <label class="layui-form-label">被授权人</label>
		    <div class="layui-input-block">
		      <input type="text" id="u_search" placeholder="请输入被授权人名称" autocomplete="off" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item" id="auth_list">
	    	<label class="layui-form-label">可授权列表</label>
		    <div class="layui-input-block">
		      	<table class="layui-hide" id="tbl_ulist" lay-filter=tbl_ulist></table>
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">开始时间</label>
		    <div class="layui-input-block">
		      <input type="text" id="auth_start" placeholder="yyyy-MM-dd" class="layui-input">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">结束时间</label>
		    <div class="layui-input-block">
		      <input type="text" id="auth_end" placeholder="yyyy-MM-dd" class="layui-input">
		    </div>
	  	</div>	  	
	</form>
</script>

<script type="text/javascript">
var table = layui.table;
var laypage = layui.laypage;
var laydate = layui.laydate;
var form = layui.form;
var curopt = "";
var _currpage = 1;
var _pageSize = 20;
var start_date = "";
var end_date = "";
var tblulist = "";

$("#c_start").blur(function(){
	laydate.render({
	    elem: '#c_start'
	    ,value: myparser($('#c_start').val())
	    ,format: 'yyyy-MM-dd'
	});
});

$("#c_end").blur(function(){
	laydate.render({
	    elem: '#c_end'
	    ,value: myparser($('#c_end').val())
	    ,format: 'yyyy-MM-dd'
	});
});

layui.use([], function(){
	var today = new Date();
	var strYear = today.getFullYear();
	var strDay = pad(today.getDate(), 2);
	var strMonth = pad(today.getMonth(), 2);
    //debugger;
    start_date = (strYear + '-' + strMonth + '-' + strDay);
    end_date =  dateFormat('YYYY-mm-dd',today);
	//初始赋值
	laydate.render({
	    elem: '#c_start'
	    ,value: start_date
	    ,format: 'yyyy-MM-dd'
	    ,isInitValue: true
	});
    laydate.render({
    	elem: '#c_end'
    	,value: end_date
    	,format: 'yyyy-MM-dd'
    	,isInitValue: true
    });
	getData(_currpage,_pageSize);
	
	
});

$('#ckpassword').on('keydown', function (event) {
    if (event.keyCode == 13) {
    	userckopt();
		layer.closeAll();
    }
});

function dialog_add(){
	curopt = "add";
	$('#user_id').val("");
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "添加授权" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['500px', '620px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#authadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     //其中：layero是弹层的DOM对象
			     renderuserlist('');
			     laydate.render({
			 	    elem: '#auth_start'
			 	    ,type: 'datetime'
			 	});
			     laydate.render({
			     	elem: '#auth_end'
			     	,type: 'datetime'
			     });
			     $('#u_user').css('display','none');
			     $('#auth_list').css('display','');
			 	 form.render();
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	//debugger;
		    	u_add('','');
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#useradd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    //$("#useradd").css('display','none'); 
			    
		 }
	});
}

function u_add(ckname,ckpassword){
	//var userdata = table.checkStatus('tbl_ulist');
	var row = $('#user_id').val();
	var datastring;
	if(row != ""){
		if($("#auth_start").val().length < 6 || $("#auth_end").val().length < 6){
			layer.msg("请输入授权时间");	
			return;
		}
		if(curopt == "add"){
			
			datastring = '{"id":"'+ row +'","stime":"' +  $("#auth_start").val()  +  '","etime":"' +  $("#auth_end").val()  + '","rname":"系统管理/授权管理/新增或修改","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "rightAuthAdd.do?",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
					if(msg.status == "1"){
						layer.closeAll();
						layer.msg(msg.desc, {
			        		  icon: 1,
			        		  time: 1000 
			        	});	
						getData(_currpage,_pageSize);									
					}else if(msg.status == "1211"){
						$('#ckname').val('');
						$('#ckpassword').val('');
						//debugger;
						ckdialgo_auth();
		        		
					}else{
						layer.msg(msg.desc, {
			        		  icon: 2,
			        		  time: 2000 
			        	});	
					}
		        						
					
		        },
		        error : function(e){
		        	if(e.status == 200){
		        		parent.location.href = "login";
		        	}else{
		        		alert(e.status);
		                alert(e.responseText);
		        	}
		        }

			});	
		}else if(curopt == "edit"){
			var checkStatus = table.checkStatus('tbl_auth');
			datastring = '{"id":"'+ row +'","authid":"' + checkStatus.data[0].id + '","stime":"' +  $("#auth_start").val()  +  '","etime":"' +  $("#auth_end").val()  + '","rname":"系统管理/授权管理/新增或修改","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "rightAuthEdit.do?",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
					if(msg.status == "1"){
						layer.closeAll();
						layer.msg(msg.desc, {
			        		  icon: 1,
			        		  time: 1000 
			        	});	
						getData(_currpage,_pageSize);									
					}else if(msg.status == "1211"){
						$('#ckname').val('');
						$('#ckpassword').val('');
						//debugger;
						ckdialgo_auth();
		        		
					}else{
						layer.msg(msg.desc, {
			        		  icon: 2,
			        		  time: 2000 
			        	});	
					}
		        						
					
		        },
		        error : function(e){
		        	if(e.status == 200){
		        		parent.location.href = "login";
		        	}else{
		        		alert(e.status);
		                alert(e.responseText);
		        	}
		        }

			});	
		}
	}else{
		layer.msg("请先选择被授权用户!", {
  		  icon: 2,
  		  time: 2000 
  	});	
	}
}

function dialog_edit(){
	curopt = "edit";
	var checkStatus = table.checkStatus('tbl_auth');
	
	if(checkStatus.data.length > 0){
		var win = layer.open({
			  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
			  ,title: "编辑授权" //标题
			  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
			  ,area: ['500px', '320px'] //宽度、高度
			  ,shade: 0.3
			  ,offset: 'auto'
			  ,anim:5 //弹出动画
			  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
			  ,content: $("#authadd").html()     //内容
			  ,btn: ['确定', '取消'] //只是为了演示
			  ,success:function(layero){
				     var mask = $(".layui-layer-shade");
				     mask.appendTo(layero.parent());
				     //其中：layero是弹层的DOM对象
				     renderuserlist(checkStatus.data[0].to_username);
				     laydate.render({
				 	    elem: '#auth_start'
				 	    ,format: 'yyyy-MM-dd HH:mm:ss'
				 	    ,type: 'datetime'
				 	    ,value: checkStatus.data[0].start_time
				 	});
				     laydate.render({
				     	elem: '#auth_end'
				     	,format: 'yyyy-MM-dd HH:mm:ss'
				     	,type: 'datetime'
				     	,value: checkStatus.data[0].end_time
				     });
				     $('#u_search').val(checkStatus.data[0].to_username);
				     $('#u_search').attr("disabled","disabled");
				     $('#u_user').css('display','');
				     $('#auth_list').css('display','none');
				     //debugger;
				 	 form.render();
				}
			,yes: function(index, layero){
			    //按钮【按钮一】的回调
			    	//debugger;
			    	u_add('','');
				 	 
			  }
			  ,btn2: function(index, layero){
			    //按钮【按钮二】的回调
			    
			    	//$("#useradd").css('display','none'); 
			    	
			  }
			  ,cancel: function(){ 
				    //右上角关闭回调
				    //$("#useradd").css('display','none'); 
				    
			 }
		});
	}else{
		layer.msg("请选择授权项!",{
			icon: 2,
			time: 2000
		})
	}
	
}

function u_cancel(ckname,ckpassword){
	curopt = "cancel";
	var userdata = table.checkStatus('tbl_auth');
	if(userdata.data.length == 0){
		layer.msg('请先选择授权项!');
		return;
	}
	
	var row = userdata.data[0];
	if (row){
		//debugger;
		var datastring = '{"id":"'+row.id+'","rname":"系统管理/授权管理/撤消授权","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
		layer.confirm('确定要撤销该授权?', {
			  btn: ['取消', '确定'] //可以无限个按钮				  
			}, function(index, layero){
			  //按钮【按钮一】的回调
				layer.closeAll();
			}, function(index){
				$.ajax({
					type:"post",
					contentType: "application/json;charset=UTF-8",
					url: "rightAuthCancel.do?",
					async:false,
					data:datastring,
			     	dataType:"json",
			        success: function(msg) {    //数据提交成功时返回数据
						if(msg.status == "1"){
							layer.closeAll();
							getData(_currpage,_pageSize);									
						}else if(msg.status == "1211"){
							$('#ckname').val('');
							$('#ckpassword').val('');							
							ckdialgo_auth();
			        		
						}else{
							layer.msg(msg.desc,{icon: 2,time: 2000});
						}						
						
			        },
			        error : function(e){
			        	if(e.status == 200){
			        		parent.location.href = "login";
			        	}else{
			        		alert(e.status);
			                alert(e.responseText);
			        	}
			        }

			});	
		});
							
	}else{
		layer.msg('需选择用户!');
	}							
}

function ckdialgo_auth(){
	layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "复核" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '260px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#dlgck")     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     //var mask = $(".layui-layer-shade");
			     //mask.appendTo(layero.parent());
			     $('#ckname').focus();
			     //其中：layero是弹层的DOM对象
			}
		 ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	userckopt();
	    		$("#dlgck").css('display','none');
			 	layer.close(index);
		    	
			 	 
		  }
		  ,btn2: function(index, layero){
		    	//按钮【按钮二】的回调
		    
		    	$("#dlgck").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    $("#dlgck").css('display','none'); 
			    
		 }
	});
}

function renderuserlist(to_username){
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getUserlistbyauth.do?",
		type : "get",
		dataType : "json",
		async: false,
		success : function(msg) {			
			tblulist = table.render({
				  elem: '#tbl_ulist'
				  //,toolbar: '#toolbarDemo'
				  ,cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
				  ,cols: [[
					 {type:'radio',hide: true}
					,{field:'username', title: '用户名'} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
				    ,{field:'orgname', title: '所属部门'}
				    ,{field:'realname', title: '姓名'}
				  ]]
				  ,data:msg
				  ,height: parent.iframeH - 240
				  ,done: function (res, curr, count){
					  
					  if(to_username != ''){
						  var that = this.elem.next();
						  res.data.forEach(function (item, index) {
				                if (item.username == to_username) {
				                	//debugger;
				                	$('#user_id').val(item.id);
				                  	//var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
				                 	 //tr.css("background-color", "yellow");
				                 	// tr.addClass('layui-table-click');
				                  	// tr.find('i[class="layui-anim layui-icon"]').trigger("click");
				                } 
				            });
					  }					  
				  }
				});		
			
		},
        error : function(e){
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
        }
	});
	
	table.on('row(tbl_ulist)', function(obj){
	    var data = obj.data;    
	    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		//选中radio样式
		obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
	    $('#u_search').val(data.username);
	    $('#user_id').val(data.id);
	});
}

  
function doSearch(){
	start_date = $('#c_start').val();
	end_date = $('#c_end').val();
	_currpage = 1;
	getData(_currpage,_pageSize);
}

function getData(pageNumber,pageSize){
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"start":"' + start_date + '","end":"' + end_date + '","ckname":"","ckpassword":""}';
	var layeri = layer.load(2);
	//debugger;
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getRightAuthList.do?",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			tablerender(msg);
			page(msg);
			if(msg.status != "1"){
				layer.msg(msg.desc);
			}
			layer.close(layeri);
		},
        error : function(e){
        	layer.close(layeri);
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
        }
	});
}

function tablerender(data){	
	table.render({
		  elem: '#tbl_auth'
		  //,toolbar: '#toolbarDemo'
		  ,cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
		  ,cols: [[
			 {type:'radio', hide: true}
			,{field:'from_username', title: '授权人'} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
		    ,{field:'to_username', title: '被授权人'}
		    ,{field:'start_time', title: '开始时间'}
		    ,{field:'end_time', title: '结束时间'}
		    ,{field:'status', title: '状态', align: 'center', templet: '#statusTpl'}
		    ,{field:'createtime', title: '创建时间'}
		  ]]
		  ,data:data.datas
		  ,limit: data.pageSize
		  ,height: parent.iframeH - 60
		});		
}

function numpage(pageNumber, pageSize) {
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"start":"' + start_date + '","end":"' + end_date + '","ckname":"","ckpassword":""}';
	var layeri = layer.load(2);
	//debugger;
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getRightAuthList.do?",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			tablerender(msg);
			layer.close(layeri);
		},
        error : function(e){
        	layer.close(layeri);
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
        }
	});
}

function page(data) {
    laypage.render({
        elem: 'page', //注意，这里的 page 是 ID，不用加 # 号
        count: data.total, //数据总数，从服务端得到
        limit: data.pageSize,  // 每页条数
        limits: [10, 20, 30, 40, 50],
        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
        curr: _currpage,
        jump: function (obj, first) {
            //console.log(obj)
            //obj包含了当前分页的所有参数，比如：
            //layer.msg(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //console.log(obj.limit); //得到每页显示的条数

            //首次不执行
            if (!first) {
                //do something
                _currpage = obj.curr;
                _pageSize = obj.limit;
                numpage(obj.curr, obj.limit)  // 分页点击传参 
            }
        }
    });
}

table.on('row(tbl_auth)', function(obj){
    var data = obj.data;    
    //标注选中样式
    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
	//选中radio样式
	obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
});


  
function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "cancel"){
		u_cancel(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "add" || curopt == "edit"){
		u_add(ckname,$.base64.encode(ckpassword));
	}
	
	
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}

function dateFormat(fmt, date) {
	var ret;
    var opt = {
        "Y+": date.getFullYear().toString(),        
        "m+": (date.getMonth() + 1).toString(),     
        "d+": date.getDate().toString(),           
        "H+": date.getHours().toString(),          
        "M+": date.getMinutes().toString(),        
        "S+": date.getSeconds().toString()         
    };
    for (var k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : pad(opt[k], ret[1].length));
        };
    };
    return fmt;
}

function myparser(s){
	if (!s) return new Date();

	var y,m,d;
	var ss = (s.split('-'));
	if(ss.length > 1){
		y = parseInt(ss[0],10);
		m = parseInt(ss[1],10);
		d = parseInt(ss[2],10);
	}else{
		y = parseInt(ss[0].substring(0,4),10);
		m = parseInt(ss[0].substring(4,6),10);
		d = parseInt(ss[0].substring(6,8),10);
	}
	
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
		return new Date(y,m-1,d);
	} else {
		return new Date();
	}
}

function pad(num, n) {  
    var len = num.toString().length;  
    while(len < n) {  
        num = "0" + num;  
        len++;  
    }  
    return num;  
}  

</script>
<script type="text/html" id="statusTpl">
  {{#  if(d.status == '0'){ }}	
    <span>正常</span>
  {{#  } else if(d.status == '1') { }}
    <span style="color: #F581B1;">失效</span>
  {{#  } }}
</script>

</body>
</html>
